<template>
  <el-container>
    <el-main>
      <div class="default-main ba-table-box">
        <TableHeader
          :buttons="[
            'refresh',
            'add',
            'edit',
            'remove',
            'comSearch',
            'columnDisplay',
          ]"
          :quick-search-placeholder="placeholder"
          @action="baTable.onTableHeaderAction"
        />
        <!-- 表格 -->
        <!-- 要使用`el-table`组件原有的属性，直接加在Table标签上即可 -->
        <Table ref="tableRef" @action="baTable.onTableAction" />
        <!-- 问题跟踪表单 -->
        <PopupForm ref="formRef" v-if="baTable.form.operate" />
      </div>
    </el-main>
  </el-container>
</template>
<script lang="ts" setup>
import _ from "lodash";
import { ref, provide, onMounted, markRaw } from "vue";
import baTableClass from "@/utils/baTable";
import { baTableApi, operatorShowOff, DictOperation } from "@/utils/common"; // 导入表格api方法生成器
import Table from "@/components/table/index.vue";
import TableHeader from "@/components/table/header/index.vue";
import useCurrentInstance from "@/utils/useCurrentInstance";
import type { TableRow, TableColumn } from "@/utils/baTable"; //表格列行类型
import { FollowProlem } from "@/api/backend/index";
import PopupForm from "./popupForm.vue";
import { useRoute, useRouter } from "vue-router";
import { useNavTabs } from "@/store/navTabs";
import { useAssetGateway } from "@/store/backend/Assets/gateway";
import { useDictionary } from "@/store/backend/tool/dictionary";
import TagSearchTemp from "./components/tempProcate.vue";
import { useAssetCabinet } from "@/store/backend/Assets/cabinet";
import { useAssetSite } from "@/store/backend/Assets/site";
import { ElNotification } from "element-plus";
import type { FormInstance } from "element-plus";
import { useBoardProcessPull } from "@/store/backend/Board/processPull";
import { useDept } from "@/store/backend/SysM/dept";
import { useUser } from "@/store/backend/SysM/user";
import { useFollowProlem } from "@/store/backend/Board/followProlem";

const placeholder = ref<string>("模糊搜索");
const tableRef = ref();
const route = useRoute();
const router = useRouter();
const navTabs = useNavTabs();
const gateway = useAssetGateway();
const dictionary = useDictionary();
const cabinet = useAssetCabinet();
const site = useAssetSite();
const dept = useDept();
const user = useUser();
const processPull = useBoardProcessPull();
const followProlem = useFollowProlem();

//字段显隐记忆功能
const filedShowOff = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(
      route.path + "/" + filter
    );
  }
  return true;
};
// 每页个数记忆功能
const pageSizeKeep = () => {
  if ((navTabs as any).pageSizeMap) {
    return (navTabs as any).pageSizeMap.get(route.path + FollowProlem)
      ? (navTabs as any).pageSizeMap.get(route.path + FollowProlem)
      : 10;
  }
  return 10;
};

//初始化字典处理类
const dictOperation = new DictOperation();

//获取字典
const getDictionary = () => {
  //获取问题域的字典
  dictOperation.getDictionary(
    followProlem,
    "sys_problem_area",
    "proCate",
    "type"
  );
  //获取晨会问题状态的字典
  dictOperation.getDictionary(
    followProlem,
    "sys_problem_status",
    "proStatus",
    "statusType"
  );
};
getDictionary();

//全局事件总线
const { proxy } = useCurrentInstance();
const baTable = new baTableClass(
  new baTableApi(FollowProlem), //this.api = api菜单管理相关
  {
    pk: "id",
    column: [
      { type: "selection", align: "center", operator: false },
      {
        show: filedShowOff("goodNo"),
        label: "料号",
        prop: "goodNo",
        align: "center",
        fixed: "left",
        width: 150,
        operatorPlaceholder: "精确搜索",
      },
      {
        show: filedShowOff("meetingDate"),
        label: "日期",
        prop: "meetingDate",
        align: "center",
        fixed: "left",
        width: 130,
        operator: false,
      },
      {
        show: filedShowOff("proCate"),
        label: "问题域",
        prop: "proCate",
        align: "center",
        fixed: "left",
        width: 110,
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(TagSearchTemp),
      },
      {
        show: filedShowOff("problems"),
        label: "问题",
        prop: "problems",
        align: "left",
        width: 220,
        operator: false,
        render: "customTemplate",
        customTemplate: (row: TableRow, field: TableColumn, value: any) => {
          if (value) {
            return "<p style='white-space: pre-line;'>" + value + "</p>";
          }
          return (
            "<p style='white-space: pre-line;text-align:center;'>" +
            "-" +
            "</p>"
          );
        },
      },
      {
        show: filedShowOff("proStatus"),
        label: "问题状态",
        prop: "proStatus",
        align: "center",
        width: 100,
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(TagSearchTemp),
        render: "customTemplate",
        customTemplate: (row: TableRow, field: TableColumn, value: any) => {
          if (value == "未处理") {
            return "<p style='color:red'>" + value + "</p>";
          } else if (value == "已完成") {
            return "<p style='color:#26bf96'>" + value + "</p>";
          } else if (value == "处理中") {
            return "<p style='color:#ffae0f'>" + value + "</p>";
          } else if (value == "0") {
            return (
              "<p style='color:red'>" +
              followProlem.tags.proStatus[value - 0] +
              "</p>"
            );
          } else if (value == "1") {
            return (
              "<p style='color:#26bf96'>" +
              followProlem.tags.proStatus[value - 0] +
              "</p>"
            );
          } else if (value == "2") {
            return (
              "<p style='color:#ffae0f'>" +
              followProlem.tags.proStatus[value - 0] +
              "</p>"
            );
          }
          return "<p>" + "-" + "</p>";
        },
      },
      {
        show: filedShowOff("proProc"),
        label: "问题处理",
        prop: "proProc",
        align: "left",
        width: "200",
        operator: false,
        render: "customTemplate",
        customTemplate: (row: TableRow, field: TableColumn, value: any) => {
          if (value) {
            return "<p style='white-space: pre-line;'>" + value + "</p>";
          }
          return (
            "<p style='white-space: pre-line;text-align:center;'>" +
            "-" +
            "</p>"
          );
        },
      },
      {
        show: filedShowOff("procEmp2"),
        label: "处理人",
        prop: "procEmp2",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("createTime"),
        label: "创建时间",
        prop: "createTime",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("modifyTime"),
        label: "更新时间",
        prop: "modifyTime",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("sheetNo"),
        label: "工单",
        prop: "sheetNo",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("dept"),
        label: "部门",
        prop: "dept",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("cemter"),
        label: "工作中心",
        prop: "cemter",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("equp"),
        label: "机台",
        prop: "equp",
        align: "center",
        operator: false,
      },
      {
        show: operatorShowOff([route.path + "/edit", route.path + "/remove"]),
        label: "操作",
        align: "center",
        width: "130",
        render: "buttons",
        fixed: "right",
        operator: false,
        buttons: [
          {
            render: "tipButton",
            name: "edit",
            title: "编辑",
            text: "",
            type: "primary",
            icon: "iconfont icon-pencil",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
          // {
          //   render: "tipButton",
          //   name: "info",
          //   title: "详情",
          //   text: "",
          //   type: "primary",
          //   icon: "iconfont icon-chaxunyujisuan",
          //   class: "table-row-edit",
          //   disabledTip: false,
          //   // 按钮是否显示，请返回布尔值
          //   display: (row: TableRow, field: TableColumn) => {
          //     return true;
          //   },
          //   // 按钮是否禁用，请返回布尔值
          //   disabled: (row: TableRow, field: TableColumn) => {
          //     return false;
          //   },
          //   attr: {},
          // },
          {
            render: "confirmButton",
            name: "remove",
            title: "删除",
            text: "",
            type: "danger",
            icon: "el-icon-DeleteFilled",
            class: "table-row-delete",
            popconfirm: {
              confirmButtonText: "删除",
              cancelButtonText: "取消",
              confirmButtonType: "danger",
              title: "确定删除所选项吗",
            },
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
        ],
      },
    ],
    filter: {
      pageSize: pageSizeKeep(),
    },
    extend: {
      column: true, //是否合并行
      columnFiled: ["goodsNo", "goodReqDate", "crequests"], //该字段相同合并
    },
  },
  {
    // 默认表单数据(添加)
    // defaultItems: {
    //   siteOrder: 1,
    //   siteType: 0, //0为地区类型
    // },
  },
  {
    onSubmit: ({
      formEl,
      operate,
      items,
    }: {
      formEl: FormInstance | undefined;
      operate: string;
      items: anyObj;
    }) => {
      console.log("表单提交前", formEl, operate, items);
      return true;
    },
  }
);

//打开晨会问题跟踪表单
const infoButtonClick = (name: string, row: any) => {
  if (!row) return;
  // 数据来自表格数据,未重新请求api,深克隆,不然可能会影响表格
  let rowClone = _.cloneDeep(row);
  console.log("打开晨会问题跟踪表单row", row);
  baTable.form.extend!["problem"] = rowClone;
  baTable.form.operate = "problem";
  // router.push({ path: "/admin/FollowProlem/iotDetail" });
};

onMounted(() => {
  baTable.table.ref = tableRef.value;
  baTable.mount();
  baTable.getList(FollowProlem);

  /**
   * 表格内的按钮响应
   * @param name 按钮name
   * @param row 被操作行数据
   */
  proxy.eventBus.on(
    "onTableButtonClick",
    (data: { name: string; row: TableRow }) => {
      if (!baTable.activate) return;
      //回滚功能暂无
      if (data.name == "rollback") {
        // onRollback([data.row[baTable.table.pk!]])
      } else if (data.name == "info") {
        //携带主键字段pk
        infoButtonClick(
          (data.row as TableRow)[baTable.table.pk!],
          data.row as any
        );
      }
    }
  );
});

// 实例化表格后，将 baTable 的实例提供给上下文
provide("baTable", baTable);
provide("gateway", gateway);
provide("dictionary", dictionary);
provide("cabinet", cabinet);
provide("site", site);
provide("dictOperation", dictOperation);
provide("processPull", processPull);
provide("dept", dept);
provide("user", user);
provide("followProlem", followProlem);
</script>
<style lang="scss" scoped>
.el-main {
  padding: 0;
  // white-space: pre; //保留回车和空格并且不会自动换行

  // white-space: pre-line; //保留回车,多个连续的空格只保留一个,且会自动换行

  // white-space: pre-wrap; //保留回车,所有的空格并且会自动换行

  // white-space: nowrap; //强制不换行

  // //word-break针对非CJK脚本的断行规则(CJK脚本是中国，日本和韩国（"中日韩"）脚本。)
  // word-break: break-all; //允许在单词内换行
  // word-break: keep-all; //只能在半角空格或连字符处换行
}
.default-main {
  margin: var(--ba-main-space) var(--ba-main-space) 60px var(--ba-main-space);
}
</style>
